package com.cqw.auth.utils;


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: Jackson转换工具类
 * @author cqw
 * @date 2020年08月14日 09:53:55
 */
@Slf4j
@NoArgsConstructor
public class JacksonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));
    }

    /**
     * 对象转json字符串
     * @param src
     * @return
     */
    public static String parseStr(Object src) {
        if (src == null) {
            return null;
        }
        try {
            return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
            log.error("解析对象:[{}]为字符串异常，错误", src, e);
        }
        return null;
    }

    /**
     * 字符串转对象
     * @param src
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObj(String src, Class<T> clazz) {
        if (null == src || null == clazz) {
            return null;
        }
        try {
            return objectMapper.readValue(src, clazz);
        } catch (Exception e) {
            log.error("解析json为对象异常，String：{}，T：{}，error：{}", src, clazz, e);
        }
        return null;
    }

}
